import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import kotlinproject.composeapp.generated.resources.Res
import kotlinproject.composeapp.generated.resources._941735022379
import kotlinproject.composeapp.generated.resources._951735022410
import kotlinproject.composeapp.generated.resources._961735022446
import kotlinproject.composeapp.generated.resources._971735022470
import kotlinproject.composeapp.generated.resources.img
import kotlinproject.composeapp.generated.resources.test1
import org.jetbrains.compose.resources.painterResource

@Composable
fun App3(modifier: Modifier = Modifier) {

    val imageUrls = listOf(
        painterResource(Res.drawable.img),
        painterResource(Res.drawable._961735022446),
        painterResource(Res.drawable._941735022379),
        painterResource(Res.drawable._951735022410),
        painterResource(Res.drawable._971735022470),
        painterResource(Res.drawable.test1)
    )

    val pagerState = rememberPagerState { imageUrls.size }
    var componentWidth = 0
    var componentHeight = 0
    var isBoundary by remember { mutableStateOf(true) } // 是否触摸到边界
    var type by remember { mutableStateOf(0) }
    var changePage by remember { mutableStateOf(false) }

    LaunchedEffect(changePage) {
        when (type) {
            1 -> pagerState.animateScrollToPage(pagerState.currentPage + 1)
            2 -> pagerState.animateScrollToPage(pagerState.currentPage - 1)
        }
    }

    HorizontalPager(
        state = pagerState,
        modifier = modifier
            .fillMaxSize()
            .onSizeChanged { size ->
                componentWidth = size.width
                componentHeight = size.height
            }
    ) { pageIndex ->
        // 每个页面的缩放和偏移状态
        var scale by remember { mutableStateOf(1f) }
        var offset by remember { mutableStateOf(Offset.Zero) }

        // 手势处理
        val gestureState = rememberTransformableState { zoomChange, panChange, _ ->
            changePage = !changePage
            type = 0
            // 缩放处理（限制在 1x-3x）
            scale = (scale * zoomChange).coerceIn(1f, 3f)
            // 平移处理（限制边界）
            if (scale > 1f) {
                val maxOffset = calculateMaxOffset(scale, componentWidth, componentHeight)
                val newOffsetX = offset.x + panChange.x
                val newOffsetY = offset.y + panChange.y
                if (newOffsetX >= maxOffset.x) {
                    if (isBoundary) {
                        type = 2
                        isBoundary = false
                    } else {
                        isBoundary = true
                        offset = Offset(maxOffset.x, newOffsetY)
                    }
                } else if (newOffsetX <= -maxOffset.x) {
                    if (isBoundary) {
                        type = 1
                        isBoundary = false
                    } else {
                        isBoundary = true
                        offset = Offset(-maxOffset.x, newOffsetY)
                    }
                } else {
                    isBoundary = false
                    offset = Offset(
                        x = (newOffsetX).coerceIn(-maxOffset.x, maxOffset.x),
                        y = (newOffsetY).coerceIn(-maxOffset.y, maxOffset.y)
                    )
                }
            } else {
                type = if (panChange.x > 0) 2 else 1
                isBoundary = true
                offset = Offset.Zero
            }
        }

        // 图片显示
        Box(
            modifier = Modifier
                .fillMaxSize()
                .transformable(gestureState)
        ) {
            Image(
                painter = imageUrls[pageIndex],
                contentDescription = null,
                contentScale = ContentScale.FillWidth,
                modifier = Modifier
                    .fillMaxWidth()
                    .align(Alignment.Center)
                    .graphicsLayer {
                        scaleX = scale
                        scaleY = scale
                        translationX = offset.x
                        translationY = offset.y
                    }
            )
        }
    }

}

// 计算最大偏移量（根据缩放比例）
private fun calculateMaxOffset(scale: Float, screenWidth: Int, screenHeight: Int): Offset {
    // 假设图片宽高占满屏幕，放大后的边界偏移量为 (scale - 1) * 屏幕尺寸 / 2
    return Offset(
        x = (scale - 1) * screenWidth / 2, // screenWidth 需要实际获取
        y = (scale - 1) * screenHeight / 2 // screenHeight 需要实际获取
    )
}
